<?php
require('../include/init.inc.php');
$method = $action = $id = '';
extract($_REQUEST, EXTR_IF_EXISTS);


$products = AdminProducts::getAllProducts();

if (Common::isGet()) {

    if ($action == 'del') {
        $product = AdminProducts::getProductById($id);

        if (!$product) {
            Common::exitWithError(ErrorMessage::PRODUCT_NOT_EXIST, "snap/products.php");
        }

        $where = array('products_id' => $id);
        $ret = AdminProducts::delete($where);
        if ($ret) {
            SysLog::addLog(UserSession::getUserName(), 'Del', 'ProductsDel', $id, json_encode($where));
            Common::exitWithSuccess('删除完成', 'snap/products.php');
        } else {
            OSAdmin::alert("error");
        }
    }

    if ($action == 'up') {
        $product = AdminProducts::getProductById($id);

        if (!$product) {
            Common::exitWithError(ErrorMessage::PRODUCT_NOT_EXIST, "snap/products.php");
        }

        $data = array('products_index' => '1');

        $where = array('products_id' => $id);
        $ret = AdminProducts::update($where, $data);

        $where_no = " WHERE products_id != " . $id;
        $data_no = array('products_index' => '0');
        AdminProducts::update($where_no, $data_no);//把其余产品全部下架 只能有一个产品展示
        if ($ret) {
            SysLog::addLog(UserSession::getUserName(), 'Update', 'ProductsUpdate', $id, json_encode($data));
            Common::exitWithSuccess('更新完成', 'snap/products.php');
        } else {
            OSAdmin::alert("error");
        }
    }

    if ($action == 'down') {
        $product = AdminProducts::getProductById($id);

        if (!$product) {
            Common::exitWithError(ErrorMessage::PRODUCT_NOT_EXIST, "snap/products.php");
        }

        $data = array('products_index' => '0');

        $where = array('products_id' => $id);
        $ret = AdminProducts::update($where, $data);
        if ($ret) {
            SysLog::addLog(UserSession::getUserName(), 'Update', 'ProductsUpdate', $id, json_encode($data));
            Common::exitWithSuccess('更新完成', 'snap/products.php');
        } else {
            OSAdmin::alert("error");
        }
    }
}


$confirm_html = OSAdmin::renderJsConfirm("icon-remove");
Template::assign('osadmin_action_confirm', $confirm_html);
Template::assign('products', $products);
Template::display('snap/products.tpl');